﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using SharpSvn;

namespace VSCodeReview
{
    internal sealed class SvnClient : IDisposable
    {
        private readonly SharpSvn.SvnClient client;

        public SvnClient()
        {
            client = new SharpSvn.SvnClient();
        }

        public bool IsVersioned(string fileName)
        {
            return client.GetUriFromWorkingCopy(fileName) != null;
        }

        public Uri GetUri(string fileName)
        {
            return client.GetUriFromWorkingCopy(fileName);
        }

        public string GetBugtraqUrl(string path)
        {
            var directoryInfo = new DirectoryInfo(path);
            while (directoryInfo != null && directoryInfo.Parent != null && (client.GetUriFromWorkingCopy(directoryInfo.Parent.FullName)) != null)
            {
                directoryInfo = directoryInfo.Parent;
            }
            if (directoryInfo == null)
            {
                return null;
            }
            var target = new SvnPathTarget(directoryInfo.FullName);
            SvnPropertyValue arg;
            if (!client.GetProperty(target, "bugtraq:url", out arg) || arg == null)
            {
                return null;
            }
            return arg.StringValue;
        }

        #region Implementation of IDisposable

        public void Dispose()
        {
            client.Dispose();
        }

        #endregion
    }
}